package vip.liux.front.adapter.controller;

import io.micrometer.observation.annotation.Observed;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.togglz.core.Feature;
import org.togglz.core.manager.FeatureManager;
import vip.liux.core.model.NameValue;

import java.util.List;
import java.util.Set;

@Observed(name = "features")
@RestController
@RequestMapping("/api/features")
public class FeatureController {

    private static final Logger log = LoggerFactory.getLogger(FeatureController.class);
    private final FeatureManager featureManager;

    public FeatureController(FeatureManager featureManager) {
        this.featureManager = featureManager;
    }

    @GetMapping("/list")
    public List<String> getFeatures() {
        List<String> list = featureManager.getFeatures().stream().map(Feature::name).toList();
        log.debug("Features: {}", list);
        return list;
    }


    @GetMapping("/all")
    public List<NameValue<Boolean>> getFeatureAl() {
        List<NameValue<Boolean>> list = featureManager.getFeatures().stream().map(x->new NameValue<>(x.name(),x.isActive())).toList();
        log.debug("Features actives: {}", list);
        return list;
    }

    @GetMapping("/enable")
    public ResponseEntity<?> enable(String featureName) {
        Set<Feature> features = featureManager.getFeatures();
        Feature feature = features.stream().filter(s -> StringUtils.equals(featureName, s.name()))
                .findFirst().orElseThrow(() -> new IllegalArgumentException("Feature not found"));
        featureManager.enable(feature);
        return ResponseEntity.noContent().build();
    }

    @GetMapping("/disable")
    public ResponseEntity<?> disable(String featureName) {
        Set<Feature> features = featureManager.getFeatures();
        Feature feature = features.stream().filter(s -> StringUtils.equals(featureName, s.name()))
                .findFirst().orElseThrow(() -> new IllegalArgumentException("Feature not found"));
        featureManager.disable(feature);
        return ResponseEntity.noContent().build();
    }
}
